<?php
if (!function_exists('is_login')) {

    function is_login() {
        $user = session('user_auth');
        if (empty($user)) {
            return 0;
        } else {
            return session('data_auth_sign') == data_auth_sign($user) ? $user['id'] : 0;
        }
    }
}

if (!function_exists('is_admin')) {

    function is_admin() {
        return UID === 1 ? true : false;
    }
}

if (!function_exists('convertUnderline')) {

    /*
     * 下划线转驼峰
     */
    function convertUnderline($str) {
        $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
            return strtoupper($matches[2]);
        }, $str);
        return ucfirst($str);
    }
}

if (!function_exists('humpToLine')) {

    /*
     * 驼峰转下划线
     */
    function humpToLine($str) {
        $str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
            return '_' . strtolower($matches[0]);
        }, $str);
        return substr($str, 1);
    }
}

if (!function_exists('parse_attr')) {

    /**
     * 解析配置
     *
     * @param string $value
     *            配置值
     * @return array|string
     */
    function parse_attr($value = '') {
        $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
        if (strpos($value, ':')) {
            $value = array();
            foreach ($array as $val) {
                list ($k, $v) = explode(':', $val);
                $value[$k] = $v;
            }
        } else {
            $value = $array;
        }
        return $value;
    }
}
if (!function_exists('list_to_config')) {

    /**
     * list转换为config
     *
     * @param
     *            $list
     * @param string $key
     * @param string $value
     * @param
     *            $value2
     * @return string[]
     */
    function list_to_config($list, $key = 'id', $value = 'title', $value2 = null) {
        $list_config = array();

        foreach ($list as $data) {
            $content = $data[$value];
            if (isset($value2)) {
                $content .= ' - ' . $data[$value2];
            }
            $list_config[$data[$key]] = $content;
        }
        return $list_config;
    }
}

if (!function_exists('get_config_text')) {

    /**
     * 获取配置值
     *
     * @param string $config_name
     *            配置标识
     * @param string $key
     *            配置值
     * @return array|string
     */
    function get_config_text($config_name = '', $key = 0) {
        $list = config($config_name);
        if (!empty($list) && isset($list[$key])) {
            return $list[$key];
        } else {
            return $key;
        }
    }
}

if (!function_exists('get_list_text')) {

    /**
     * 获取配置值
     *
     * @param string $config_name
     *            配置标识
     * @param string $key
     *            配置值
     * @return array|string
     */
    function get_list_text($list, $key = 0) {
        if (strpos($key, ',')) {
            $keys = explode(',', $key);
            $str = '';
            foreach ($list as $k => $v) {
                if (in_array($k, $keys)) {
                    $str .= $v . ', ';
                }
            }
            return substr($str, 0, strlen($str) - 2);
        } else {
            return $list[$key];
        }
    }
}

if (!function_exists('get_status_html')) {

    /**
     * 获取状态Html文本
     *
     * @param number $status
     * @return number
     */
    function get_status_html($status = 1) {
        $html = $status;
        switch ($status) {
            case 1:
                $html = '<span class="label label-success label-badge">正常</span>';
                break;
            case 0:
                $html = '<span class="label label-warning label-badge">禁用</span>';
                break;
            case -1:
                $html = '<span class="label label-danger label-badge">删除</span>';
                break;
            default:
                $html = $status;;
                break;
        }
        return $html;
    }
}

if (!function_exists('get_audit_html')) {

    /**
     * 获取状态Html文本
     *
     * @param number $status
     * @return number
     */
    function get_audit_html($status = 1) {
        $html = $status;
        switch ($status) {
            case 9:
                $html = '<span class="label label-success label-badge">已通过</span>';
                break;
            case 1:
                $html = '<span class="label label-info label-badge">未审核</span>';
                break;
            case 0:
                $html = '<span class="label label-warning label-badge">不通过</span>';
                break;
            case -1:
                $html = '<span class="label label-danger label-badge">删除</span>';
                break;
            default:
                $html = $status;;
                break;
        }
        return $html;
    }
}

if (!function_exists('get_audit_clazz')) {

    /**
     * 获取状态Html文本
     *
     * @param number $status
     * @return number
     */
    function get_audit_clazz($status = 1) {
        $clazz = '';
        switch ($status) {
            case 9:
                $clazz = 'audit-pass';
                break;
            case 1:
                $clazz = 'audit-not';
                break;
            case 0:
                $clazz = 'audit-failed';
                break;
            case -1:
                $clazz = '';
                break;
            default:
                $clazz = '';
                break;
        }
        return $clazz;
    }
}

if (!function_exists('rand_string')) {

    function rand_string($len = 8, $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
        return substr(str_shuffle($str), 0, $len);
    }
}
if (!function_exists('create_doc_number')) {

    /**
     * 创建订单编码
     */
    function create_doc_number($type = 'common', $name, $suffix_len = 4, $prefix_str = '') {
        $map = array();
        $map['type'] = $type;
        $map['name'] = $name;
        $data = db('doc_number')->where($map)->find();
        if ($data) {
            $doc_number = $data['number'] + 1;
            $data['number'] = $doc_number;
            $data['update_time'] = time();
            $data['update_by'] = UID;
            db('doc_number')->update($data);
            return $prefix_str . $name . str_prefix($doc_number, $suffix_len, 0);
        } else {
            $doc_number = 1;

            $data['name'] = $name;
            $data['type'] = $type;
            $data['number'] = $doc_number;
            $data['update_time'] = time();
            $data['update_by'] = UID;
            db('doc_number')->insert($data);

            return $prefix_str . $name . str_prefix($doc_number, $suffix_len, 0);
        }
    }
}

if (!function_exists('create_order_number')) {

    /**
     * 创建托运单号
     *
     * @return string
     */
    function create_order_number() {
        // return create_doc_number('order', date("ymd", time()), 4, '');
        $name = '';
        while (true) {
            $name = 'D' . date("ymd", time()) . rand_string(4, '0123456789');
            $map = array();
            $map['name'] = $name;
            $data = db('order')->where($map)->find();
            if ($data == null) {
                break;
            }
        }

        return $name;
    }
}
if (!function_exists('create_shipment_number')) {

    /**
     * 创建托运单号
     *
     * @return string
     */
    function create_shipment_number() {
        // return create_doc_number('order', date("ymd", time()), 4, '');
        $name = '';
        while (true) {
            $name = 'F' . date("ymd", time()) . rand_string(4, '0123456789');
            $map = array();
            $map['name'] = $name;
            $data = db('order')->where($map)->find();
            if ($data == null) {
                break;
            }
        }
        return $name;
    }
}

if (!function_exists('num_to_rmb')) {

    /**
     * 数字金额转换成中文大写金额的函数
     * String Int $num 要转换的小写数字或小写字符串
     * return 大写字母
     * 小数位为两位
     */
    function num_to_rmb($num) {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        // 精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        // 将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                // 获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            // 每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            // 去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            // 结束循环
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            // utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            // 处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }
        // 这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }
        // 将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }
    }
}

if (!function_exists('str_prefix')) {

    function str_prefix($str, $n = 1, $char = "0") {
        $str_len = strlen($str);
        for ($x = 0; $x < $n - $str_len; $x++) {
            $str = $char . $str;
        }
        return $str;
    }
}

if (!function_exists('get_top_menus')) {

    function get_top_menus() {
        $menus = config('azthink.menus');
        $top_menus = array();
        foreach ($menus as $menu) {
            if ($menu['pid'] === 0) {
                array_push($top_menus, $menu);
            }
        }
        return $top_menus;
    }
}

if (!function_exists('get_menus')) {

    function get_menus($pid) {
        $menus = config('azthink.menus');
        $_menus = array();
        foreach ($menus as $menu) {
            if ($menu['pid'] === $pid) {
                array_push($_menus, $menu);
            }
        }
        return $_menus;
    }
}
if (!function_exists('get_client_ip')) {

    /**
     * 获取客户端IP
     *
     * @return string
     */
    function get_client_ip() {
        static $ip = '';
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_CDN_SRC_IP'])) {
            $ip = $_SERVER['HTTP_CDN_SRC_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] as $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }
}
if (!function_exists('data_auth_sign')) {

    /**
     * 数据签名认证
     *
     * @param array $data
     *            被认证的数据
     * @return string 签名
     */
    function data_auth_sign($data) {
        // 数据类型检测
        if (!is_array($data)) {
            $data = (array)$data;
        }
        ksort($data); // 排序
        $code = http_build_query($data); // url编码并生成query字符串
        $sign = sha1($code); // 生成签名
        return $sign;
    }
}

if (!function_exists('get_district_text')) {

    /**
     * 数据签名认证
     *
     * @param array $data
     *            被认证的数据
     * @return string 签名
     */
    function get_district_text($district_ids, $district_config) {
        // 数据类型检测
        $ids = array();
        if (!is_array($district_ids)) {
            $ids = explode(',', $district_ids);
        }
        $titles = array();
        foreach ($ids as $id) {
            array_push($titles, $district_config[$id]);
        }
        return implode(', ', $titles);
    }
}

if (!function_exists('raw_order_status')) {

    function raw_order_status($status) {
        $order_status = config('azthink.order_status');
        $clazz = 'default';
        switch ($status) {
            case 0:
                $clazz = 'danger';
                break;
            case 1:
                $clazz = 'default';
                break;
            case 2:
                $clazz = 'info';
                break;
            case 3:
                $clazz = 'primary';
                break;
            case 8:
                $clazz = 'success';
                break;
            case 9:
                $clazz = 'success';
                break;
        }

        return '<span class="label label-' . $clazz . '">' . $order_status[$status] . '</span>';
    }
}

if (!function_exists('raw_shipment_status')) {

    function raw_shipment_status($status) {
        $order_status = config('azthink.shipment_status');
        $clazz = 'default';
        switch ($status) {
            case 0:
                $clazz = 'danger';
                break;
            case 1:
                $clazz = 'info';
                break;
            case 2:
                $clazz = 'primary';
                break;
            case 3:
                $clazz = 'success';
                break;
        }

        return '<span class="label label-' . $clazz . '">' . $order_status[$status] . '</span>';
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 格式化字节大小
     *
     * @param number $size
     *            字节数
     * @param string $delimiter
     *            数字和单位分隔符
     * @return string 格式化后的带单位的大小
     * @author 艺品网络 <twothink.cn>
     */
    function format_bytes($size, $delimiter = '') {
        $units = array(
            'B',
            'KB',
            'MB',
            'GB',
            'TB',
            'PB'
        );
        for ($i = 0; $size >= 1024 && $i < 5; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('parse_config_attr')) {
    // 分析枚举类型配置值 格式 a:名称1,b:名称2
    function parse_config_attr($string) {
        $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
        if (strpos($string, ':')) {
            $value = array();
            foreach ($array as $val) {
                list($k, $v) = explode(':', $val);
                $value[$k] = $v;
            }
        } else {
            $value = $array;
        }
        return $value;
    }
}

if (!function_exists('list_to_tree')) {
    /**
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     * @author 李忠 <ny_lizhong@126.com>
     */
    function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = '0') {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer [$data [$pk]] = &$list [$key];
            }


            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data [$pid];
                if ($root == $parentId) {
                    $tree [] = &$list [$key];
                } else {
                    if (isset ($refer [$parentId])) {
                        $parent = &$refer [$parentId];
                        $parent [$child] [] = &$list [$key];
                    }
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('tree_to_list')) {
    /**
     * 将list_to_tree的树还原成列表
     *
     * @param array $tree原来的树
     * @param string $child孩子节点的键
     * @param string $order排序显示的键，一般是主键 升序排列
     * @param array $list过渡用的中间数组，
     * @return array 返回排过序的列表数组
     * @author yangweijie <yangweijiester@gmail.com>
     */
    function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array()) {
        if (is_array($tree)) {
            foreach ($tree as $key => $value) {
                $reffer = $value;
                if (isset ($reffer [$child])) {
                    unset ($reffer [$child]);
                    tree_to_list($value [$child], $child, $order, $list);
                }
                $list [] = $reffer;
            }
            $list = list_sort_by($list, $order, $sortby = 'asc');
        }
        return $list;
    }
}
//if (!function_exists('get_addon_class')) {
//    /**
//     * 获取插件类的类名
//     * @param strng $name 插件名
//     */
//    function get_addon_class($name) {
//        $class = "\\addons\\" . strtolower($name) . "\\{$name}";
//        return $class;
//    }
//}
if (!function_exists('export_excel')) {
    /**
     * 导出Excel
     * @param  object $spreadsheet 数据
     * @param  string $format 格式:excel2003 = xls, excel2007 = xlsx
     * @param  string $savename 保存的文件名
     * @return filedownload         浏览器下载
     */
    function export_excel($data_header, $data_body, $savename = 'export', $format = 'xlsx') {



        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle($savename);
        for ($i = 0; $i < count($data_header); $i++) {
            $worksheet->setCellValueByColumnAndRow($i + 1, 1, $data_header[$i]);
        }

        foreach ($data_body as $row=>$data){
            foreach ($data as $column=>$value){
                $worksheet->setCellValueByColumnAndRow($column + 1, $row+2, $value);
            }
        }
        $savename .= date('Ymd');

        if ($format == 'xls') {
            //输出Excel03版本
            header('Content-Type:application/vnd.ms-excel');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
        } elseif ($format == 'xlsx') {
            //输出07Excel版本
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
        }
        //输出名称
        header('Content-Disposition: attachment;filename="' . $savename . '.' . $format . '"');
        //禁止缓存
        header('Cache-Control: max-age=0');
        $writer = new $class($spreadsheet);
        $filePath = env('runtime_path') . "temp/" . time() . microtime(true) . ".tmp";
        $writer->save($filePath);
        readfile($filePath);
        unlink($filePath);
    }
}

if (!function_exists('export_excel_spreadsheet')) {
    /**
     * 导出Excel
     * @param  object $spreadsheet 数据
     * @param  string $format 格式:excel2003 = xls, excel2007 = xlsx
     * @param  string $savename 保存的文件名
     * @return filedownload         浏览器下载
     */
    function export_excel_spreadsheet($spreadsheet, $savename = 'export', $format = 'xlsx') {
        if (!$spreadsheet) return false;
        if ($format == 'xls') {
            //输出Excel03版本
            header('Content-Type:application/vnd.ms-excel');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
        } elseif ($format == 'xlsx') {
            //输出07Excel版本
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
        }
        //输出名称
        header('Content-Disposition: attachment;filename="' . $savename . '.' . $format . '"');
        //禁止缓存
        header('Cache-Control: max-age=0');
        $writer = new $class($spreadsheet);
        $filePath = env('runtime_path') . "temp/" . time() . microtime(true) . ".tmp";
        $writer->save($filePath);
        readfile($filePath);
        unlink($filePath);
    }
}
